#
# 能量清单模块
#


import datetime

from rasa_sdk.executor import CollectingDispatcher
from typing import Text, Dict, Any, List

from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet, SessionStarted, UserUtteranceReverted
from actions import common
import requests
import re
import time


def current_thought(tracker):
    num = tracker.get_slot('thought_3_change_1')
    cur = 'thought_' + str(num)
    text = tracker.get_slot(cur)
    return text


def conversation_rounds(tracker, **type):
    try:
        if common.rediscommon().get(tracker.current_state()['sender_id'] + '-wx-block-module2'):
            r = common.rediscommon()
            userid = tracker.current_state()['sender_id']
            r.set(userid + 'TempTimeSteame', str(time.time()), ex=86400)
            common.rediscommon().delete(tracker.current_state()['sender_id'] + '-wx-block-module2')
            return []
    except:
        pass
    if 'type' in type:
        if type['type'] == 1:
            userid = tracker.current_state()['sender_id']
            conn = common.POOL.connection(shareable=False)
            cursor = conn.cursor()
            cursor.execute(
                "Select * from `user_result` where topic_type=3 and is_end=0 and user_info_id ='" + userid + "' order by create_time desc")
            x = cursor.fetchone()
            sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",is_part_know=1 where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
            common.connectmysql(sql)
            return []

    userid = tracker.current_state()['sender_id']
    conn = common.POOL.connection(shareable=False)
    cursor = conn.cursor()
    cursor.execute(
        "Select * from `user_result` where topic_type=3 and is_end=0 and user_info_id ='" + userid + "' order by create_time desc")
    x = cursor.fetchone()
    if x[18] not in [(),None,]:
        r = common.rediscommon()
        try:
            temp = float(r.get(userid + 'TempTimeSteame'))
        except:
            temp = 0
        timenow = time.time()
        c = round(timenow - temp, 3)
        if x[18] == 0.001:
            sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",response_time=" + str(
                c) + " where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
            common.connectmysql(sql)
        else:
            sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",response_time=" + str(x[
                                                                                                                   18] + c) + " where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
            common.connectmysql(sql)
        r.set(userid + 'TempTimeSteame', str(time.time()), ex=86400)
    else:
        r = common.rediscommon()
        r.set(userid + 'TempTimeSteame', str(time.time()), ex=86400)
        sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",response_time=0.000 where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
        common.connectmysql(sql)
    return []


class part12_1_1_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_1_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='是这样的，因为音乐可以对你的心理和情绪健康产生巨大的影响🧠。它可以成为应对糟糕情绪和困难环境非常强大的工具。', buttons=[
            {'payload': '/button_part12_1_2_choose_1', 'title': '啊~我明白了', 'life': 1},
            {'payload': '/button_part12_1_2_choose_1', 'title': '有点意思', 'life': 1}, ])
        return [SlotSet('playlist_slot_1', None), SlotSet('playlist_slot_2', None), SlotSet('playlist_slot_3', None)]


class part12_1_2_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_2_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='科学家们对这个主题进行了大量研究。 例如，密苏里大学的一项研究证明，有意识地听乐观的音乐可以在短短两周内改善一个人的情绪。', buttons=[
            {'payload': '/button_part12_1_3_choose_1', 'title': '哇哦!', 'life': 1},
            {'payload': '/button_part12_1_3_choose_1', 'title': '有趣', 'life': 1}, ])
        return []


class part12_1_3_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_3_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(
            text='但是音乐也可以对我们的感觉和思想产生更复杂的影响。 脑成像研究表明，听音乐会激活大脑中的许多重要结构……包括海马体，它在维持记忆和形成社会依恋方面上起着至关重要的作用。', buttons=[
                {'payload': '/button_part12_1_4_choose_1', 'title': '酷', 'life': 1},
                {'payload': '/button_part12_1_4_choose_1', 'title': '你想说什么？', 'life': 1}, ])
        return []


class part12_1_4_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_4_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='这意味着音乐可以在我们沮丧时起到振奋精神这样简单的功能。 但它也可以让我们想起那些更轻松、更快乐的时光，以及我们最关心的人。 ♥', buttons=[
            {'payload': '/button_part12_1_5_choose_1', 'title': '我深有体会♥', 'life': 1}, ])
        return []


class part12_1_5_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_5_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='虽然，我对你还不够了解......但随着世界上发生的一切，我所接触的很多人都感到灰心和担忧，或者想念他们已经有一段时间没能见到的亲人。  ', buttons=[
            {'payload': '/button_part12_1_6_choose_1', 'title': '是呀……我也是', 'life': 1},
            {'payload': '/button_part12_1_6_choose_2', 'title': '其实我感觉还行', 'life': 1}, ])
        return []


class part12_1_6_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_6_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='唉，听到这话我很难过……现在的时代很艰难，我们都不熟悉，也都没有准备。🙁。不过我有个好主意……', buttons=[
            {'payload': '/button_part12_1_7_choose_1', 'title': '是什么？', 'life': 1}, ])
        return []


class part12_1_6_choose_2(Action):
    def name(self) -> Text:
        return "action_part12_1_6_choose_2"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='我很高兴听到这个消息! 你一定是一个坚强的、有韧性的人💪。我有一个建议，如果感觉状况不好时，这可能对你有帮助......', buttons=[
            {'payload': '/button_part12_1_7_choose_1', 'title': '是什么？', 'life': 1}, ])
        return []


class part12_1_7_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_7_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='还记得你刚想出来的那三首歌吗？当你发现自己在挣扎时，可以听歌振作起你的精神，提醒你过去那些美好的时光，并且帮助你感受到与你所想念的人的联系。',
                                 buttons=[
                                     {'payload': '/button_part12_1_8_choose_1', 'title': '好主意', 'life': 1}, ])
        return []


class part12_1_8_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_8_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        cursor.execute(
            "Select * from `user_result` where topic_type=3 and is_end=0 and user_info_id ='" + userid + "' order by create_time desc")
        x = cursor.fetchone()
        result_id = x[0]
        sql = "Select * from user_tools_response where user_result_id ='" + result_id + "' and user_info_id='" + userid + "' order by create_time desc limit 1"
        cursor.close()
        conn.close()
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        cursor.execute(sql)
        y = cursor.fetchone()
        sing1 = y[26]
        sing2 = y[27]
        sing3 = y[28]
        if sing1 == None:
            sing1 = ''
        if sing2 == None:
            sing2 = ''
        if sing3 == None:
            sing3 = ''
        dispatcher.utter_message(
            text='因此，下次你可能会感到困在家里，对发生的一切感到焦虑，或与你的社交网圈子有距离......在这些艰难的时刻，请听' + sing1 + '、' + sing2 + '或' + sing3 + '。- 在这些艰难的时刻，它可能正是你所需要的。',
            buttons=[
                {'payload': '/button_part12_1_9_choose_1', 'title': '明白啦', 'life': 1},
                {'payload': '/button_part12_1_9_choose_1', 'title': '我会哒', 'life': 1}, ])
        cursor.close()
        conn.close()
        return []


class part12_1_9_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_9_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='你可以全部把三首歌都听一遍......或添加更多你喜欢的歌曲来建立一个更长的播放列表', buttons=[
            {'payload': '/button_part12_1_10_choose_1', 'title': '🎵我肯定会这样做的!', 'life': 1}, ])
        return []


class part12_1_10_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_10_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='在任何情况下，我希望你能找到自己的方式，用音乐来缓解你的心灵，并与对你很重要的人和记忆保持联系。音乐真的可以成为一个强大的工具! 🛠️', buttons=[
            {'payload': '/button_part12_1_11_choose_1', 'title': '🛠️好的！', 'life': 1}, ])
        return []


class part12_1_11_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_11_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        dispatcher.utter_message(text='在你结束之前，可以告诉我，你觉得我们这次聊天怎么样吗？', buttons=[
            {'payload': '/button_part12_1_12_choose_1', 'title': '好', 'life': 1},
            {'payload': '/button_part12_1_12_choose_1_2', 'title': '不好', 'life': 1}, ])
        return []


class part12_1_12_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_12_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
            x = cursor.fetchone()
            result_id = x[0]
            if tracker.current_state()['events'][-2]['text'] == '/button_part12_1_12_choose_1':
                sql = "update user_tools_response set evaluation_playlist='好' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
            if tracker.current_state()['events'][-2]['text'] == '/button_part12_1_12_choose_1_2':
                sql = "update user_tools_response set evaluation_playlist='不好' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
            common.connectmysql(sql)
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x050')
            return [UserUtteranceReverted()]
        finally:
            cursor.close()
            conn.close()
        dispatcher.utter_message(text='谢谢你告诉我你的意见，这对我很有帮助，特别是当我想在这些快速变化的时代里，探索出如何更好地帮助人类的时候', buttons=[
            {'payload': '/button_part12_1_13_choose_1', 'title': '不客气~', 'life': 1}, ])
        return []


class part12_1_13_choose_1(Action):
    def name(self) -> Text:
        return "action_part12_1_13_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        userid = tracker.current_state()['sender_id']
        sql = "update `user_result` set `is_end` = 1,end_time=now() where `user_info_id`='" + userid + "' and `topic_type` = 3 and `is_end` = 0 order by create_time desc limit 1;"
        common.connectmysql(sql)
        dispatcher.utter_message(text='嗯嗯，我很高兴你今天来找我聊天。要好好照顾自己哦，我很快会再和你联系的,你已完成当天的实验流程', buttons=[
            {'payload': '/greet', 'title': '拜拜小E', 'life': 1}, ])
        return []

    class action_ask_playlist_slot_1(Action):
        def name(self) -> Text:
            return "action_ask_playlist_slot_1"

        async def run(
                self,
                dispatcher: CollectingDispatcher,
                tracker: Tracker,
                domain: Dict[Text, Any],
        ) -> List[Dict[Text, Any]]:
            conversation_rounds(tracker)
            dispatcher.utter_message(text="什么歌曲总是会让你感到精力充沛或变得乐观呢？请在下面输入框中写入歌名，不要点击选项✏ ")
            return []


class action_ask_playlist_slot_2(Action):
    def name(self) -> Text:
        return "action_ask_playlist_slot_2"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
            x = cursor.fetchone()
            result_id = x[0]
            sql = "update `user_tools_response` set playlist_energy='" + tracker.get_slot('playlist_slot_1') + "' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
            common.connectmysql(sql)
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x020')
            return [UserUtteranceReverted()]
        finally:
            cursor.close()
            conn.close()
        dispatcher.utter_message(text="好的。那么，说出一首让你想起你生命中的某个时刻的歌，那是一个你感到特别有希望、快乐或无忧无虑的时刻。 ✏ ")
        return []


class action_ask_playlist_slot_3(Action):
    def name(self) -> Text:
        return "action_ask_playlist_slot_3"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(tracker)
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
            x = cursor.fetchone()
            result_id = x[0]
            sql = "update `user_tools_response` set playlist_happy_time='" + tracker.get_slot('playlist_slot_2') + "' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
            common.connectmysql(sql)
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x020')
            return [UserUtteranceReverted()]
        finally:
            cursor.close()
            conn.close()
        dispatcher.utter_message(text="最后，有没有一首歌能让你想起生活中的某个特别的人，她可以是朋友、伴侣或者你的家人。✏️")
        return []

    class action_playlist_save_1(Action):
        def name(self) -> Text:
            return "action_playlist_save_1"

        async def run(
                self,
                dispatcher: CollectingDispatcher,
                tracker: Tracker,
                domain: Dict[Text, Any],
        ) -> List[Dict[Text, Any]]:
            conversation_rounds(tracker)
            userid = tracker.current_state()['sender_id']
            conn = common.POOL.connection(shareable=False)
            cursor = conn.cursor()
            try:
                cursor.execute(
                    "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
                x = cursor.fetchone()
                result_id = x[0]
                sql = "update `user_tools_response` set playlist_friend='" + tracker.get_slot('playlist_slot_3') + "' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
                common.connectmysql(sql)
            except:
                dispatcher.utter_message(text='机器人错误 错误码0x020')
                return [UserUtteranceReverted()]
            finally:
                cursor.close()
                conn.close()
            dispatcher.utter_message(text="非常感谢你的分享。 你可能会想知道为什么我首先问你这些问题......", buttons=[
                {'payload': '/button_part12_1_1_choose_1', 'title': '是……为什么呢？？', 'life': 1}])
            return []


class action_build_power(Action):
    def name(self) -> Text:
        return "action_build_power"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_info` where `id` = '" + userid + "';")
            x = cursor.fetchone()
            nickname = x[1]
            names = x[2]
            test_batch=str(x[35])
            if nickname is None:
                nickname = ''
            if names is None:
                names = ''
            sql = "insert into `user_result`(`id`,`user_info_id`,`topic_type`,`name`,`conversation_rounds`,`nick_name`,`test_batch`) values('" + common.getuid() + "','" + userid + "',3,'" + names + "',0,'" + nickname + "',"+str(x[35])+");"
            common.connectmysql(sql)
            cursor.close()
            conn.close()
            conn = common.POOL.connection(shareable=False)
            cursor = conn.cursor()
            #重新连接数据库
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
            x = cursor.fetchone()
            sql = "insert into `user_tools_response` (`id`,`user_info_id`,`user_result_id`,`name`,`use_tools`,`nick_name`,`test_batch`) values('" + common.getuid() + "','" + \
                  x[1] + "','" + x[0] + "','" + names + "','能量清单','" + nickname + "',"+test_batch+");"
            common.connectmysql(sql)
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x006')
            return [UserUtteranceReverted()]
        finally:
            cursor.close()
            conn.close()
        conversation_rounds(tracker)
        dispatcher.utter_message(text="现在，我有一个问题想要问你......", buttons=[
            {'payload': '/actives_playlist_form1', 'title': '是什么？', 'life': 1}], json_message={"module_type": 2,"word_module_type":6})
        return []
